import json
import time


def readjson(jsonname):
    try:
        with open(jsonname, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except:
        createJsonFile(jsonname)
        with open(jsonname, 'r', encoding='utf-8') as f:
            data = json.load(f)
    return data

def savejson(data,jsonname):
    # Writing JSON data
    with open(jsonname, 'w',encoding='utf-8') as f:
        json.dump(data, f,ensure_ascii=False, indent=4)


def createJsonFile(jsonname):
    initJson = {}
    savejson(initJson, jsonname)

def jsonDataAdd(jsonname,userName,num,machineinfo,nowtime):
    userjson = readjson(jsonname)
    DataTime = time.strftime('%Y%m%d', time.localtime(time.time()))
    name = userName
    numm = num
    userjson[name] = [numm, DataTime,machineinfo,nowtime]
    savejson(userjson, jsonname)

# json清空记录初始化
def jsonDateInit(jsonname):
    userjson = readjson(jsonname)
    DataTime = time.strftime('%Y%m%d', time.localtime(time.time()))
    for user in userjson:
        userjson[user][0] = 0
        userjson[user][1] = DataTime
    savejson(userjson,jsonname)
    print('json初始化成功')

def jsonClearAllUsers(jsonname):
    userjson = readjson(jsonname)
    userjson.clear()
    savejson(userjson,jsonname)

def deletUser(username,jsonname):
    userjson = readjson(jsonname)
    if username in userjson:
        userjson.pop(username)
        savejson(userjson,jsonname)
        print(f"成功删除用户:{username}")
    else:
        print("不存在该用户")

def getUserPOSTNum(username,jsonname):
    userjson = readjson(jsonname)
    if username in userjson:
        return userjson[username][0]
    else:
        print("不存在该用户")


if __name__ == '__main__':
    jsonname ='user.json'
    deletUser('用户名',jsonname)   #删除用户
    #
    # jsonDataAdd(jsonname,'xiaohong',3) #增加用户
    #
    # jsonDateInit(jsonname)  #初始化用户次数
    # jsonClearAllUsers(jsonname)

    # getUserPOSTNum('xiaohu', jsonname)  #

    # createJsonFile(jsonname)  #初始化
